import EmptyLayout from '@/layout/empty'
import { formatTreeData } from '@/utils/util-array'

const modules = import.meta.glob('../views/*/*.vue')

/**
 * 格式化菜单数据
 * @param data 菜单数据
 * @returns {{home: Object, menus: Array}}
 */
export function formatMenus (data) {
  let home = false
  const menus = formatTreeData(data, (d) => {
    const item = Object.assign({}, d)
    item.meta = Object.assign({
      icon: item.icon,
      title: item.title
    }, item.meta)
    if (!item.children?.length) {
      if (!home && item.path) {
        home = item
      }
    } else if (item.children[0].path) {
      const cp = item.children[0].path
      if (!item.redirect) {
        item.redirect = cp
      }
      if (!item.path) {
        item.path = cp.substring(0, cp.lastIndexOf('/'))
      }
    }
    if (!item.path) {
      console.error('菜单的path作为vue循环的key不能为空且要唯一: ', d)
      return false
    }
    return item
  })
  return { menus, home }
}

/**
 * 菜单数据转成路由数据
 * @param menus 菜单数据
 * @returns {Array}
 */
export function menuToRoutes (menus) {
  if (!menus?.length) {
    return null
  }
  const routes = []
  menus.forEach((item) => {
    const path =
      item.path && item.path.includes('?')
        ? item.path.substring(0, item.path.indexOf('?'))
        : item.path
    if (path) {
      const meta = Object.assign({}, item.meta)
      let component
      if (item.component) {
        component = modules['../views' + item.component + '.vue']
      } else {
        component = EmptyLayout
      }
      routes.push({
        meta: meta,
        name: item.path,
        path: item.path,
        component: component,
        redirect: item.redirect || undefined,
        children: menuToRoutes(item.children)
      })
    }
  })
  return routes
}

/**
 * 获取默认展开菜单map
 * @param menu
 * @param deep
 * @returns {{}}
 */
export const getOpenKeysMap = (menu, deep = false) => {
  let map = {}
  for (let i = 0; i < menu.length; i++) {
    if ('children' in menu[i]) {
      let menuSub = menu[i].children
      for (let j = 0; j < menuSub.length; j++) {
        let subPath = menuSub[j].path
        map[subPath] = deep ? deep.concat([menu[i].path]) : [menu[i].path]
        if ('children' in menuSub[j]) {
          map = Object.assign(map, getOpenKeysMap(menuSub[j].children, map[subPath].concat([subPath])))
        }
      }
    } else if (deep) {
      map[menu[i].path] = deep
    }
  }
  return map
}
